/* eslint-disable vue/valid-v-bind */
<template>
  <div class="main">
    <!-- 保存可以参考这个方法 -->
    <!-- <div @click="onUpload">保存</div> -->
    <!-- //顶部上传按钮 -->
    <button
      type="button"
      class="xunzeimage"
      @click="onPickFile"
    > 点击上传</button>
    <!-- {{ name }} -->
    <!-- //把下面input隐藏,代替它选择文件 -->

    <input
      ref="fileInput"
      type="file"
      accept="image/*"
      style="display: none"
      @change="uploadImg"
    />
    <!-- //选择文件 -->
    <CropImage
      :visible="cropperVisible"
      :url="file"
      :auto-crop-width="autoCropWidth"
      :auto-crop-height="autoCropHeight"
      @cancel="cropperVisible = false"
      @confirm="onConfirm"
    />
  <!-- <img :src="imageUrl" /> -->
  <!-- //绑定文件地址 -->
  </div>
</template>

<script>
import axios from "axios"; // 获取上传的链接
import CropImage from '@/components/CropImage'
export default {
  components: {
    CropImage
  },
  props: {
    pestvalue: {
      type: String,
      default: () => ''
    }
  },
  // name: "whatever",
  data() {
    return {
      accessToken: '',
      image: '',
      imageUrl: "", // img绑定的src地址
      postUrl: this.$baseurl.webServiceUrl + "v3/pestsDistinguish/cleverPlanting/saveIm", // 需要上传到的地址
      name: "",
      cropperVisible: false,
      autoCropWidth: 1024,
      autoCropHeight: 1024,
      file: null
    };
  },
  watch: {
    accessToken: {
      handler (newData) {
        this.accessToken = newData
      },
      // 立即监听
      immediate: true,
      // 深度监听
      deep: true
    }
    // pestvalue: {
    //   handler(e) {
    //     this.image = ''
    //     this.imageUrl = ''
    //   }
    // }
  },
  mounted() {
    // 第一步:先请求一下api,看看需要上传到哪里去,存到postUrl里面 ( 做了跨域配置,所以直接写成了api )
    // axios.get("api/getUploadInfo?type=image").then(res => {
    //   if (res.status === 200 && res.data) {
    //     let data = res.data.data;
    //     let postUrl = data.url;
    //     console.log(postUrl); //页面挂载后,先打印一下,拿到了需要上传到的url地址   ( 第一次有效打印 )
    //     this.postUrl = postUrl; //把地址保存下来
    //   }
    // });
  },
  methods: {
    setaccessToken(e) {
      this.accessToken = e
    },
    // /growthProcessPicture/query/{pictureId}
    // 图片查询接口, 根据id获取图片
    // 第二步:再来写个方法, button代替input选择图片
    onPickFile() {
      this.$refs.fileInput.click();
    },
    // 第三步: 文件选择后, 后在页面上显示出来    转base64位的操作
    getFile(event, w, h) {
      const files = event.target.files;
      let filename = files[files.length - 1].name; // 只有一个文件
      this.name = filename
      this.$emit('imagename', filename)
      if (filename.lastIndexOf(".") <= 0) {
        return alert("请添加一张图片!"); // 判断图片是否有效
      }
      const fileReader = new FileReader(); // 内置方法new FileReader()   读取文件
      fileReader.readAsBinaryString(files[files.length - 1]);
      fileReader.addEventListener("load", () => {
        this.imageUrl = window.btoa(fileReader.result.toString());
        this.file = 'data:image/png;base64,' + window.btoa(fileReader.result.toString())
        this.image = files[files.length - 1];
        if (w < 1024 && w > 128 && h < 1024 && h > 128) {
          this.$emit('child-event', this.imageUrl)
          let img = 'data:image/png;base64,' + window.btoa(fileReader.result.toString())
          this.onConfirm(this.base64ToBlob(img))
        } else {
          this.$emit('child-event', this.imageUrl)
          this.cropperVisible = true
        }
      });
      // fileReader.readAsBinaryString(files[files.length - 1]);
      // fileReader.onload = function(f) {
      //   this.imageUrl = fileReader.result;
      // }
      // 到这里后, 选择图片就可以显示出来了
      // console.log(this.image)
      // 子组件向父组件传值
    },

    uploadImg(event) { // 上传图片
      const _this = this;
      let _file = event.target.files[0];
      let reader = new FileReader();

      reader.readAsDataURL(_file);
      reader.onload = function(e) {
        let image = new Image();
        image.src = e.target.result;
        image.onload = function() {
          let w = this.width;
          let h = this.height;
          _this.getFile(event, w, h)
        }
      }
    },
    base64ToBlob (base64) {
      const parts = base64.split(";base64,");
      const contentType = parts[0].split(":")[1];
      const raw = window.atob(parts[1]);
      const rawLength = raw.length;

      const uInt8Array = new Uint8Array(rawLength);

      for (let i = 0; i < rawLength; i += 1) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], { type: contentType });
    },
    // 第四步: 上传文件了
    onConfirm(event) {
      // alert("ss")
      // event.preventDefault();
      let fd = new FormData(); // 内置方法new FormData()  新建一个表格
      let img = new window.File([event], this.name, { type: 'image/jpeg' })
      fd.append("file", img); // 把image添加进去
      // console.log(img); // (       第二次有效打印           )
      // console.log(this.image); // (       第二次有效打印           )
      // return
      let that = this
      axios({
        url: this.postUrl,
        method: "post",
        headers: {
          accessToken: sessionStorage.token,
          databaseName: sessionStorage.databaseName,
          organizationList: sessionStorage.organizationList,
          organizationNo: sessionStorage.organizationNo,
          virtualSystemNo: sessionStorage.virtualSystemNo,
          lesseeNo: sessionStorage.lesseeNo
        },
        data: fd
      }).then(
        res => {
          if (res.data.code === 1) {
            that.$emit('respimageurl', res.data.data.url)
            this.cropperVisible = false
          } else {
            console.log(res.data)
            this.$message.warning('请上传和品种一致的图片')
          }
        }
      )
    }
  }
};
</script>
<style scoped>
.xunzeimage{
    border: 1px solid #6ecae3;
    width: 200px;
    background-color: transparent;
    line-height: 40px;
    border-radius: 4px;
    color: rgb(161, 154, 154);
    font-weight: 600;
    /* height: 40px; */
    /* margin-left: -10px; */
}
</style>
